package com.bjb.vr.common.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.dto.ExecutedSql;
import com.bjb.vr.common.mapper.ExecutedSqlMapper;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.bjb.vr.common.vo.UmsAccountVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author admin
 * @description 针对表【executed_sql(已经执行过的SQL保存在此表中，解决数据回环问题)】的数据库操作Service实现
 * @createDate 2023-01-04 11:29:12
 */
@Slf4j
@Service
public class ExecutedSqlService extends ServiceImpl<ExecutedSqlMapper, ExecutedSql> {

    @Resource
    private ExecutedSqlMapper executedSqlMapper;


    /**
     * 设置租户信息
     *
     * @param tenantId
     */
    private static void buildTenantInfo(String tenantId) {
        UmsAccountVo accountVo = new UmsAccountVo();
        accountVo.setTenantId(tenantId);
        ThreadLocalUtil.set(ThreadLocalConstant.USER_ACCOUNT_INFO, accountVo);
    }

    /**
     * 根据SQLMD5查询
     *
     * @param statementMd5
     * @param tenantId
     * @return
     */
    public ExecutedSql queryByMd5(String statementMd5, String tenantId) {
        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
        buildTenantInfo(tenantId);
        LambdaQueryWrapper<ExecutedSql> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(statementMd5), ExecutedSql::getMd5, statementMd5);
        ExecutedSql executedSql = executedSqlMapper.selectOne(queryWrapper);
        return executedSql;
    }

    /**
     * 根据SQLMD5删除
     *
     * @param statementMd5
     * @param tenantId
     */
    public void deleteByMd5(String statementMd5, String tenantId) {
        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
        buildTenantInfo(tenantId);
        LambdaQueryWrapper<ExecutedSql> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(statementMd5), ExecutedSql::getMd5, statementMd5);
        queryWrapper.eq(StringUtils.isNotBlank(tenantId), ExecutedSql::getTenantId, tenantId);
        executedSqlMapper.delete(queryWrapper);
    }

    /**
     * 保存数据
     *
     * @param executedSql
     */
    public void saveDataToExecute(ExecutedSql executedSql) {
        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
        buildTenantInfo(executedSql.getTenantId());
        executedSqlMapper.insert(executedSql);
    }
}




